import logging
import os
from celery import Celery
from celery.utils.log import get_task_logger

from application import settings
from application.settings import BASE_DIR, CELERY_BEAT_SCHEDULE

# 1.设置临时环境变量
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'application.settings')

# 2.初始化celery的应用
app = Celery('app_group', broker='redis://xdy-redis:6379/0', backend='redis://xdy-redis:6379/1')

# 获取 Celery 自带的日志记录器
logger = get_task_logger('my_celery_logger')

redis_password = os.getenv('REDIS_PASSWORD', '000000')

app.config_from_object({
    'broker_url': f'redis://:{redis_password}@xdy-redis:6379/0',
    'result_backend': f'redis://:{redis_password}@xdy-redis:6379/1',
    'timezone': 'Asia/Shanghai',
})

# 加载 Celery beat 配置，加载 CELERY_BEAT_SCHEDULE
app.conf.update(
    CELERY_BEAT_SCHEDULE=CELERY_BEAT_SCHEDULE,
)

# 3.设置自动发现任务
app.autodiscover_tasks(settings.INSTALLED_APPS)